<?php
use JPush\Client as JPush;


if(!function_exists('jPush')){
    /**
     * [JPush 极光推送]
     * @param array   $user   [推送用户id]
     * @param string  $alert  [推送信息]
     * @param [type]  $type   [环境  true表生产环境  false 表开发环境]
     * @param boolean $is_all [description]
     */
    function JPush($user=[],$alert='',$type=false,$is_all = false){
        $client = new JPush(config('JPush.app_key'),config('JPush.secret'));
        try {
            $client = $client->push();
            $client->setPlatform('all');
            if(!mepty($user)){
                $client->addAllAudience();
            }else if($is_all){
                $client->addAlias($user);
            }else{
                return ['status'=>0,'msg'=>'未定义推送类型'];
            }
            $client->setNotificationAlert($alert);
            $client->iosNotification($alert);
            $client->androidNotification($alert);
            $client->options(['apns_production'=>$type]);
            $res = $client->send();
            return json_encode($res);
        } catch (\Exception $e) {
            return ['status'=>0,$e->getMessage()];
        }
        
    }
}

if(!function_exists('new_im')){

    /**
     * [new_im 内部方法实例化im]
     * @return [type] [description]
     */
    function new_im(){
        $jmessage = new \JMessage\JMessage(config('JPush.app_key'),config('JPush.secret'),['disable_ssl' => true ]);
        $user = new \JMessage\IM\User($jmessage);
        return $user;
    }

}




if(!function_exists('im_register')){
    /**
    * [im_register 极光im注册]
    * @param  string $user_name [description]
    * @param  string $pwd       [description]
    * @return [type]            [description]
    */
    function im_register($user_name='',$pwd=''){
        if($user_name == '' || $pwd == ''){
            return ['status'=>0,'msg'=>'参数缺失'];
        }
        $im_user = new_im();
        $res = $im_user->register($user_name,$pwd);
        if(isset($res['body'][0]['error'])){
            return ['status'=>0,'msg'=>'极光im注册失败，失败原因'.$res['body'][0]['error']['message']];
        }
        return ['status'=>1];

    }
}

/**
 * [im_update 修改im信息]
 * @param  array  $data [相关参数查看极光im]
 * @return [type]       [description]
 */
function im_update($user_name='',$data=[]){
    if(empty($data) || $user_name == ''){
        return ['status'=>0,'msg'=>'参数缺失'];
    }

    $im_user = new_im();
    $res = $im_user->update($user_name,$data);

    if(isset($res['body'][0]['error'])){
        return ['status'=>0,'msg'=>'修改信息失败，失败原因'.$res['body'][0]['error']['message']];
    }
    return ['status'=>1];
}

if(!function_exists('get_coord')){
    /**
     * 根据当前经纬度获取指定距离的坐标
     * @param $lng 经度
     * @param $lat  纬度
     * @param int $distance  距离（公里）
     * @return array
     */

    function get_coord($lng, $lat,$distance = 1){

        $earthdata = 6378.138;//地球半径，平均半径为6371km
        $dlng = 2 * asin(sin($distance / (2 * $earthdata)) / cos(deg2rad($lat)));
        $dlng = rad2deg($dlng);
        $dlat = $distance / $earthdata;
        $dlat = rad2deg($dlat);
        $arr = array(
            'left_top' => array('lat' => $lat + $dlat, 'lng' => $lng - $dlng),
            'right_top' => array('lat' => $lat + $dlat, 'lng' => $lng + $dlng),
            'left_bottom' => array('lat' => $lat - $dlat, 'lng' => $lng - $dlng),
            'right_bottom' => array('lat' => $lat - $dlat, 'lng' => $lng + $dlng)
        );
        return $arr;
    }
}


if(!function_exists('get_distance')){
    /**
     * 根据经纬度计算距离
     * @param $lat1
     * @param $lng1
     * @param $lat2
     * @param $lng2
     * @return float
     *
     */
    function get_distance($lat1, $lng1, $lat2, $lng2){
        $earthRadius = 6367000; //approximate radius of earth in meters
        $lat1 = ($lat1 * pi() ) / 180;
        $lng1 = ($lng1 * pi() ) / 180;
        $lat2 = ($lat2 * pi() ) / 180;
        $lng2 = ($lng2 * pi() ) / 180;
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;
        return round($calculatedDistance);
    }
}

if(!function_exists('timeFormat')){
    /**
     * [timeFormat 评论时间格式化]
     * @param  [type] $time [指定时间戳]
     * @return [type]       [description]
     */
    function timeFormat($time=''){
        if($time == ''){
            return $time;
        }
        if(date('Y') == date('Y',$time)){
            if(time() - $time  < 60){
                return '刚刚'; 
            }else if(time() - $time < 3600){
                return intval((time() - $time)/60).'分钟前';
            }else if(time() - $time < 3600*24){
                return intval((time() - $time)/3600).'小时前';
            }else{
                return date('m-d H:i',$time);
            }
        }else{
            return date('Y-m-d H:i',$time);
        }
      
    }
}
    